package cn.amebius.simpledocker.websocket.callback;

import com.github.dockerjava.api.async.ResultCallback;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.Closeable;
import java.io.IOException;

/**
 * @author 阿伟
 * @date 2023/9/25 1:21
 */
@Slf4j
public class TextAbstractCallback<Frame> extends ResultCallback.Adapter<com.github.dockerjava.api.model.Frame>  {

    private Closeable closeable;

    private final WebSocketSession session;

    private final String name;


    public TextAbstractCallback(String name, WebSocketSession session) {
        this.name = name;
        this.session = session;
    }

    @Override
    public void onNext(com.github.dockerjava.api.model.Frame object) {
            try {
                session.sendMessage(new BinaryMessage(object.getPayload()));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            log.info("【{}】[{}]收到消息:{}",name,session.getId(), new String(object.getPayload()));
    }

    @Override
    public void onStart(Closeable stream) {
        this.closeable = stream;
        log.info("【{}】[{}]开启callback",name,session.getId());
    }

    @Override
    public void onError(Throwable throwable) {
        log.error("【{}】[{}]出现异常:{}",name,session.getId(),throwable.getMessage());
    }

    @Override
    public void onComplete() {
        super.onComplete();
    }

    @Override
    public void close(){
        log.info("【{}】[{}]已经关闭",name,session.getId());
    }

}
